const express = require('express');
const router = express.Router();
const User = require('../models/User');
const { sendMail } = require('../config/email');
const { Op } = require('sequelize');
const { requireAuth } = require('../middleware/auth');

// 发送验证码
router.post('/send-code', async (req, res) => {
    try {
        const { email } = req.body;
        if (!email) {
            return res.status(400).json({ error: '请提供邮箱地址' });
        }

        // 检查发送频率限制
        const lastSent = await User.findOne({
            where: {
                email,
                verifyCodeExpires: {
                    [Op.gt]: new Date(Date.now() - 60000) // 1分钟内
                }
            }
        });

        if (lastSent) {
            return res.status(429).json({ error: '请稍后再试' });
        }

        // 生成6位验证码
        const verifyCode = Math.floor(100000 + Math.random() * 900000).toString();
        const expires = new Date(Date.now() + 10 * 60 * 1000); // 10分钟有效期

        // 更新或创建用户
        const [user] = await User.findOrCreate({
            where: { email },
            defaults: {
                verifyCode,
                verifyCodeExpires: expires
            }
        });

        if (user) {
            await user.update({
                verifyCode,
                verifyCodeExpires: expires
            });
        }

        // 发送验证码邮件
        await sendMail({
            to: email,
            subject: '登录验证码',
            message: `您的验证码是：${verifyCode}，10分钟内有效。`
        });

        res.json({ success: true, message: '验证码已发送' });
    } catch (error) {
        console.error('发送验证码失败:', error);
        res.status(500).json({ error: '发送验证码失败' });
    }
});

// 验证码登录
router.post('/login', async (req, res) => {
    try {
        const { email, code } = req.body;

        const user = await User.findOne({
            where: {
                email,
                verifyCode: code,
                verifyCodeExpires: {
                    [Op.gt]: new Date()
                }
            }
        });

        if (!user) {
            return res.status(401).json({ error: '验证码无效或已过期' });
        }

        // 更新登录时间并清除验证码
        await user.update({
            lastLoginAt: new Date(),
            verifyCode: null,
            verifyCodeExpires: null
        });

        // 设置会话
        req.session.userId = user.id;
        req.session.email = user.email;

        res.json({
            success: true,
            user: {
                id: user.id,
                email: user.email
            }
        });
    } catch (error) {
        console.error('登录失败:', error);
        res.status(500).json({ error: '登录失败' });
    }
});

// 检查登录状态
router.get('/check', (req, res) => {
    if (req.session.userId) {
        res.json({
            loggedIn: true,
            user: {
                id: req.session.userId,
                email: req.session.email
            }
        });
    } else {
        res.json({ loggedIn: false });
    }
});

// 退出登录
router.post('/logout', requireAuth, (req, res) => {
    req.session.destroy(err => {
        if (err) {
            console.error('退出登录失败:', err);
            return res.status(500).json({ error: '退出登录失败' });
        }
        res.json({ success: true });
    });
});

// 获取用户信息
router.get('/profile', requireAuth, async (req, res) => {
    try {
        const user = await User.findByPk(req.session.userId, {
            attributes: ['id', 'email', 'lastLoginAt', 'createdAt']
        });
        
        if (!user) {
            return res.status(404).json({ error: '用户不存在' });
        }

        res.json(user);
    } catch (error) {
        console.error('获取用户信息失败:', error);
        res.status(500).json({ error: '获取用户信息失败' });
    }
});

module.exports = router; 